package com.daxidi.cn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.daxidi.cn.entity.*;
import com.daxidi.cn.mapper.BillMapper;
import com.daxidi.cn.mapper.MemberMapper;
import com.daxidi.cn.mapper.PayMapper;
import com.daxidi.cn.mapper.ShopMapper;
import com.daxidi.cn.params.QueryPayListParam;
import com.daxidi.cn.service.IPayService;
import com.daxidi.cn.utils.BankUtil;
import com.daxidi.cn.utils.PageUtils;
import com.daxidi.cn.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 支付订单表或者退款表 服务实现类
 * </p>
 *
 * @author wsh
 * @since 2020-11-09
 */
@Service
public class PayServiceImpl extends ServiceImpl<PayMapper, Pay> implements IPayService {

    @Autowired
    private PayMapper payMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private BillMapper billMapper;

    @Override
    public void addPay(Pay pay) {
        payMapper.insert(pay);
    }

    @Override
    public void deletePayById(Integer id) {
        payMapper.deleteById(id);
    }

    @Override
    public void updatePayById(Pay pay) {
        payMapper.updateById(pay);
    }

    /**
     * 分页查询订单列表
     *
     * @param queryPayListParam
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageUtils<PaySystemListVo> queryPayListPage(QueryPayListParam queryPayListParam, Integer pageNum, Integer pageSize) {
        if (null == pageNum) {
            pageNum = 1;
        }
        if (null == pageSize) {
            pageSize = 20;
        }
        //创建分页对象
        PageUtils pageUtils = new PageUtils();
        pageUtils.setCurrentPage(pageNum);
        pageUtils.setPageNo(pageNum);
        pageUtils.setPageSize(pageSize);
        //开始分页查询
        //交易时间
        String[] payTimeArray = new String[3];
        if (null != queryPayListParam.getPayTime() && !"".equals(queryPayListParam.getPayTime())) {
            //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd");
            String payTimeStr = queryPayListParam.getPayTime().substring(0, 10);
            payTimeArray = payTimeStr.split("-");
        }
        //查询总条数
        Long totalPay = payMapper.queryPayCount(queryPayListParam, payTimeArray[0], payTimeArray[1], payTimeArray[2]);
        pageUtils.setTotalCount(totalPay);
        //查询
        List<Bill> billList = payMapper.queryPayListPage(queryPayListParam, pageUtils.getPageNo(), pageSize, payTimeArray[0], payTimeArray[1], payTimeArray[2]);
        List<PaySystemListVo> paySystemListVoList = new ArrayList<>();
        billList.forEach(bill -> {
            PaySystemListVo paySystemListVo = new PaySystemListVo();
            BeanUtils.copyProperties(bill, paySystemListVo);
            //根据shopId查询shopName
            QueryWrapper<Shop> wrapper = new QueryWrapper<>();
            wrapper.eq("id", bill.getShopId());
            paySystemListVo.setShopName(shopMapper.selectOne(wrapper).getName());
            //会员, 根据会员编号查询会员名称
            QueryWrapper<Member> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("id", bill.getMembeId());
            paySystemListVo.setMemberName(memberMapper.selectOne(wrapper2).getName());
            //支付订单号
            QueryWrapper<Pay> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("bill_id", bill.getId());
            Pay pay = payMapper.selectOne(wrapper1);
            if (ObjectUtils.isEmpty(pay)) {
                paySystemListVo.setTransactionId("未支付，无支付订单号");
            } else {
                paySystemListVo.setTransactionId(pay.getTransactionId());
            }
            paySystemListVo.setId(bill.getId());
            paySystemListVoList.add(paySystemListVo);
        });
        pageUtils.setCurrentList(paySystemListVoList);
        return pageUtils;
    }

    /**
     * 查询所有商家名称
     *
     * @return
     */
    public List<ShopNameVo> queryAllShop() {
        //查询所有的商家信息
        List<Shop> shopList = shopMapper.selectList(null);
        List<ShopNameVo> shopNameVos = new ArrayList<>();
        //遍历，添加进VO
        shopList.forEach(shop -> {
            ShopNameVo shopNameVo = new ShopNameVo();
            shopNameVo.setShopId(shop.getId());
            shopNameVo.setShopName(shop.getName());
            shopNameVos.add(shopNameVo);
        });
        return shopNameVos;
    }

    @Override
    public SystemOrderDetailsVo queryOrderDetails(String orderId) {
        OrderSystemVo orderSystemVo = new OrderSystemVo();
        WxPaySystemVo wxPaySystemVo = new WxPaySystemVo();
        //根据orderId查询bill表
        QueryWrapper<Bill> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        Bill bill = billMapper.selectOne(wrapper);
        //根据bill中的shopId查询商家名称
        QueryWrapper<Shop> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("id", bill.getShopId());
        Shop shop = shopMapper.selectOne(wrapper2);
        //根据bill中的memberId查询会员姓名
        QueryWrapper<Member> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("id", bill.getMembeId());
        Member member = memberMapper.selectOne(wrapper3);
        //根据orderId查询pay
        QueryWrapper<Pay> wrapper4 = new QueryWrapper<>();
        wrapper4.eq("out_trade_no", orderId);
        Pay pay = payMapper.selectOne(wrapper4);
        if (!ObjectUtils.isEmpty(pay)) {
            orderSystemVo.setNotifyStatus("通知成功");
            orderSystemVo.setNotifyTime(pay.getTimeEnd());
            orderSystemVo.setNotifyStatus(pay.getResultCode());
        } else if (ObjectUtils.isEmpty(pay)) {
            orderSystemVo.setNotifyStatus("通知失败");
        }
        //封装orderSystemVo
        orderSystemVo.setDiscount(bill.getDiscount());
        orderSystemVo.setDiscounted(bill.getDiscounted());
        orderSystemVo.setOrderId(bill.getOrderId());
        orderSystemVo.setTotal(bill.getTotal());
        orderSystemVo.setShopName(shop.getName());
        orderSystemVo.setMemberName(member.getName());
        orderSystemVo.setPayAt(bill.getPayAt());
        orderSystemVo.setPayState(bill.getState());
        //封装WxPaySystemVo
        if(!ObjectUtils.isEmpty(pay)){
            BeanUtils.copyProperties(pay, wxPaySystemVo);
            wxPaySystemVo.setErrCode(pay.getErrCode());
            wxPaySystemVo.setErrCodeDes(pay.getErrCodeDes());
            wxPaySystemVo.setPayStatus(bill.getState() == 1 ? "支付成功" : "支付失败");
        } else if (ObjectUtils.isEmpty(pay)) {
            wxPaySystemVo.setOutTradeNo(bill.getOrderId().toString());
            wxPaySystemVo.setMchId(shop.getSubMchId());
            wxPaySystemVo.setPayStatus("尚未支付");
        }
        wxPaySystemVo.setBank(shop.getBank());
        String whichBank = BankUtil.getNameOfBank(shop.getBank()).split("·")[0];
        wxPaySystemVo.setWhichBank(whichBank);
        //封装返回对象
        SystemOrderDetailsVo systemOrderDetailsVo = new SystemOrderDetailsVo();
        systemOrderDetailsVo.setOrderSystemVos(orderSystemVo);
        systemOrderDetailsVo.setWxPaySystemVos(wxPaySystemVo);
        return systemOrderDetailsVo;
    }
}
